3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
23 * Pager for Special:Contributions
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\Rdbms\FakeResultWrapper
;
29 use Wikimedia\Rdbms\IDatabase
;
31 class ContribsPager
extends RangeChronologicalPager
{
34 * @var string[] Local cache for escaped messages
39 * @var string User name, or a string describing an IP address range
44 * @var string Set to "newbie" to list contributions from the most recent 1% registered users.
45 * $this->target is ignored then. Defaults to "users".
50 * @var string|int A single namespace number, or an empty string for all namespaces
52 private $namespace = '';
55 * @var string|false Name of tag to filter, or false to ignore tags
60 * @var bool Set to true to invert the namespace selection
65 * @var bool Set to true to show both the subject and talk namespace, no matter which got
71 * @var bool Set to true to show only deleted revisions
76 * @var bool Set to true to show only latest (a.k.a. current) revisions
81 * @var bool Set to true to show only new pages
86 * @var bool Set to true to hide edits marked as minor by the user
90 private $preventClickjacking = false;
93 private $mDbSecondary;
101 * @var TemplateParser
103 private $templateParser;
105 public function __construct( IContextSource
$context, array $options ) {
106 parent
::__construct( $context );
115 foreach ( $msgs as $msg ) {
116 $this->messages
[$msg] = $this->msg( $msg )->escaped();
119 $this->target
= $options['target'] ??
'';
120 $this->contribs
= $options['contribs'] ??
'users';
121 $this->namespace = $options['namespace'] ??
'';
122 $this->tagFilter
= $options['tagfilter'] ??
false;
123 $this->nsInvert
= $options['nsInvert'] ??
false;
124 $this->associated
= $options['associated'] ??
false;
126 $this->deletedOnly
= !empty( $options['deletedOnly'] );
127 $this->topOnly
= !empty( $options['topOnly'] );
128 $this->newOnly
= !empty( $options['newOnly'] );
129 $this->hideMinor
= !empty( $options['hideMinor'] );
131 // Date filtering: use timestamp if available
132 $startTimestamp = '';
134 if ( $options['start'] ) {
135 $startTimestamp = $options['start'] . ' 00:00:00';
137 if ( $options['end'] ) {
138 $endTimestamp = $options['end'] . ' 23:59:59';
140 $this->getDateRangeCond( $startTimestamp, $endTimestamp );
142 // Most of this code will use the 'contributions' group DB, which can map to replica DBs
143 // with extra user based indexes or partioning by user. The additional metadata
144 // queries should use a regular replica DB since the lookup pattern is not all by user.
145 $this->mDbSecondary
= wfGetDB( DB_REPLICA
); // any random replica DB
146 $this->mDb
= wfGetDB( DB_REPLICA
, 'contributions' );
147 $this->templateParser
= new TemplateParser();
150 function getDefaultQuery() {
151 $query = parent
::getDefaultQuery();
152 $query['target'] = $this->target
;
158 * This method basically executes the exact same code as the parent class, though with
159 * a hook added, to allow extensions to add additional queries.
161 * @param string $offset Index offset, inclusive
162 * @param int $limit Exact query limit
163 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
164 * @return IResultWrapper
166 function reallyDoQuery( $offset, $limit, $order ) {
167 list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
174 * This hook will allow extensions to add in additional queries, so they can get their data
175 * in My Contributions as well. Extensions should append their results to the $data array.
177 * Extension queries have to implement the navbar requirement as well. They should
178 * - have a column aliased as $pager->getIndexField()
180 * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
181 * - have the ORDER BY specified based upon the details provided by the navbar
183 * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
185 * &$data: an array of results of all contribs queries
186 * $pager: the ContribsPager object hooked into
187 * $offset: see phpdoc above
188 * $limit: see phpdoc above
189 * $descending: see phpdoc above
191 $data = [ $this->mDb
->select(
192 $tables, $fields, $conds, $fname, $options, $join_conds
195 'ContribsPager::reallyDoQuery',
196 [ &$data, $this, $offset, $limit, $order ]
201 // loop all results and collect them in an array
202 foreach ( $data as $query ) {
203 foreach ( $query as $i => $row ) {
204 // use index column as key, allowing us to easily sort in PHP
205 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
210 if ( $order === self
::QUERY_ASCENDING
) {
217 $result = array_slice( $result, 0, $limit );
219 // get rid of array keys
220 $result = array_values( $result );
222 return new FakeResultWrapper( $result );
225 function getQueryInfo() {
226 $revQuery = Revision
::getQueryInfo( [ 'page', 'user' ] );
228 'tables' => $revQuery['tables'],
229 'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
232 'join_conds' => $revQuery['joins'],
235 if ( $this->contribs
== 'newbie' ) {
236 $max = $this->mDb
->selectField( 'user', 'max(user_id)', '', __METHOD__
);
237 $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
238 # ignore local groups with the bot right
239 # @todo FIXME: Global groups may have 'bot' rights
240 $groupsWithBotPermission = User
::getGroupsWithPermission( 'bot' );
241 if ( count( $groupsWithBotPermission ) ) {
242 $queryInfo['tables'][] = 'user_groups';
243 $queryInfo['conds'][] = 'ug_group IS NULL';
244 $queryInfo['join_conds']['user_groups'] = [
246 'ug_user = ' . $revQuery['fields']['rev_user'],
247 'ug_group' => $groupsWithBotPermission,
248 'ug_expiry IS NULL OR ug_expiry >= ' .
249 $this->mDb
->addQuotes( $this->mDb
->timestamp() )
253 // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
254 // a timestamp offset far in the past such that there are no edits by users with user_ids in
255 // the range, we would end up scanning all revisions from that offset until start of time.
256 $queryInfo['conds'][] = 'rev_timestamp > ' .
257 $this->mDb
->addQuotes( $this->mDb
->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
259 $user = User
::newFromName( $this->target
, false );
260 $ipRangeConds = $user->isAnon() ?
$this->getIpRangeConds( $this->mDb
, $this->target
) : null;
261 if ( $ipRangeConds ) {
262 $queryInfo['tables'][] = 'ip_changes';
264 * These aliases make `ORDER BY rev_timestamp, rev_id` from {@see getIndexField} and
265 * {@see getExtraSortFields} use the replicated `ipc_rev_timestamp` and `ipc_rev_id`
266 * columns from the `ip_changes` table, for more efficient queries.
267 * @see https://phabricator.wikimedia.org/T200259#4832318
269 $queryInfo['fields'] = array_merge(
271 'rev_timestamp' => 'ipc_rev_timestamp',
272 'rev_id' => 'ipc_rev_id',
274 array_diff( $queryInfo['fields'], [
279 $queryInfo['join_conds']['ip_changes'] = [
280 'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
282 $queryInfo['conds'][] = $ipRangeConds;
284 // tables and joins are already handled by Revision::getQueryInfo()
285 $conds = ActorMigration
::newMigration()->getWhere( $this->mDb
, 'rev_user', $user );
286 $queryInfo['conds'][] = $conds['conds'];
287 // Force the appropriate index to avoid bad query plans (T189026)
288 if ( isset( $conds['orconds']['actor'] ) ) {
289 // @todo: This will need changing when revision_comment_temp goes away
290 $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
291 // Alias 'rev_timestamp' => 'revactor_timestamp' so "ORDER BY rev_timestamp" is interpreted to
292 // use revactor_timestamp instead.
293 $queryInfo['fields'] = array_merge(
294 array_diff( $queryInfo['fields'], [ 'rev_timestamp' ] ),
295 [ 'rev_timestamp' => 'revactor_timestamp' ]
298 $queryInfo['options']['USE INDEX']['revision'] =
299 isset( $conds['orconds']['userid'] ) ?
'user_timestamp' : 'usertext_timestamp';
304 if ( $this->deletedOnly
) {
305 $queryInfo['conds'][] = 'rev_deleted != 0';
308 if ( $this->topOnly
) {
309 $queryInfo['conds'][] = 'rev_id = page_latest';
312 if ( $this->newOnly
) {
313 $queryInfo['conds'][] = 'rev_parent_id = 0';
316 if ( $this->hideMinor
) {
317 $queryInfo['conds'][] = 'rev_minor_edit = 0';
320 $user = $this->getUser();
321 $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
323 // Paranoia: avoid brute force searches (T19342)
324 if ( !$user->isAllowed( 'deletedhistory' ) ) {
325 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0';
326 } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
327 $queryInfo['conds'][] = $this->mDb
->bitAnd( 'rev_deleted', Revision
::SUPPRESSED_USER
) .
328 ' != ' . Revision
::SUPPRESSED_USER
;
331 // For IPv6, we use ipc_rev_timestamp on ip_changes as the index field,
332 // which will be referenced when parsing the results of a query.
333 if ( self
::isQueryableRange( $this->target
) ) {
334 $queryInfo['fields'][] = 'ipc_rev_timestamp';
337 ChangeTags
::modifyDisplayQuery(
338 $queryInfo['tables'],
339 $queryInfo['fields'],
341 $queryInfo['join_conds'],
342 $queryInfo['options'],
346 // Avoid PHP 7.1 warning from passing $this by reference
348 Hooks
::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
353 function getNamespaceCond() {
354 if ( $this->namespace !== '' ) {
355 $selectedNS = $this->mDb
->addQuotes( $this->namespace );
356 $eq_op = $this->nsInvert ?
'!=' : '=';
357 $bool_op = $this->nsInvert ?
'AND' : 'OR';
359 if ( !$this->associated
) {
360 return [ "page_namespace $eq_op $selectedNS" ];
363 $associatedNS = $this->mDb
->addQuotes(
364 MWNamespace
::getAssociated( $this->namespace )
368 "page_namespace $eq_op $selectedNS " .
370 " page_namespace $eq_op $associatedNS"
378 * Get SQL conditions for an IP range, if applicable
379 * @param IDatabase $db
380 * @param string $ip The IP address or CIDR
381 * @return string|false SQL for valid IP ranges, false if invalid
383 private function getIpRangeConds( $db, $ip ) {
384 // First make sure it is a valid range and they are not outside the CIDR limit
385 if ( !$this->isQueryableRange( $ip ) ) {
389 list( $start, $end ) = IP
::parseRange( $ip );
391 return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
395 * Is the given IP a range and within the CIDR limit?
397 * @param string $ipRange
398 * @return bool True if it is valid
401 public function isQueryableRange( $ipRange ) {
402 $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
404 $bits = IP
::parseCIDR( $ipRange )[1];
406 ( $bits === false ) ||
407 ( IP
::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
408 ( IP
::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
419 public function getIndexField() {
420 // Note this is run via parent::__construct() *before* $this->target is set!
421 return 'rev_timestamp';
425 * @return false|string
427 public function getTagFilter() {
428 return $this->tagFilter
;
434 public function getContribs() {
435 return $this->contribs
;
441 public function getTarget() {
442 return $this->target
;
448 public function isNewOnly() {
449 return $this->newOnly
;
455 public function getNamespace() {
456 return $this->namespace;
462 protected function getExtraSortFields() {
463 // Note this is run via parent::__construct() *before* $this->target is set!
467 protected function doBatchLookups() {
468 # Do a link batch query
469 $this->mResult
->seek( 0 );
471 $this->mParentLens
= [];
472 $batch = new LinkBatch();
473 $isIpRange = $this->isQueryableRange( $this->target
);
474 # Give some pointers to make (last) links
475 foreach ( $this->mResult
as $row ) {
476 if ( isset( $row->rev_parent_id
) && $row->rev_parent_id
) {
477 $parentRevIds[] = $row->rev_parent_id
;
479 if ( isset( $row->rev_id
) ) {
480 $this->mParentLens
[$row->rev_id
] = $row->rev_len
;
481 if ( $this->contribs
=== 'newbie' ) { // multiple users
482 $batch->add( NS_USER
, $row->user_name
);
483 $batch->add( NS_USER_TALK
, $row->user_name
);
484 } elseif ( $isIpRange ) {
485 // If this is an IP range, batch the IP's talk page
486 $batch->add( NS_USER_TALK
, $row->rev_user_text
);
488 $batch->add( $row->page_namespace
, $row->page_title
);
491 # Fetch rev_len for revisions not already scanned above
492 $this->mParentLens +
= Revision
::getParentLengths(
494 array_diff( $parentRevIds, array_keys( $this->mParentLens
) )
497 $this->mResult
->seek( 0 );
503 protected function getStartBody() {
504 return "<ul class=\"mw-contributions-list\">\n";
510 protected function getEndBody() {
515 * Check whether the revision associated is valid for formatting. If has no associated revision
516 * id then null is returned.
519 * @param Title|null $title
520 * @return Revision|null
522 public function tryToCreateValidRevision( $row, $title = null ) {
524 * There may be more than just revision rows. To make sure that we'll only be processing
525 * revisions here, let's _try_ to build a revision out of our row (without displaying
526 * notices though) and then trying to grab data from the built object. If we succeed,
527 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
528 * to extensions to subscribe to the hook to parse the row.
530 Wikimedia\
suppressWarnings();
532 $rev = new Revision( $row, 0, $title );
533 $validRevision = (bool)$rev->getId();
534 } catch ( Exception
$e ) {
535 $validRevision = false;
537 Wikimedia\restoreWarnings
();
538 return $validRevision ?
$rev : null;
542 * Generates each row in the contributions list.
544 * Contributions which are marked "top" are currently on top of the history.
545 * For these contributions, a [rollback] link is shown for users with roll-
546 * back privileges. The rollback link restores the most recent version that
547 * was not written by the target user.
549 * @todo This would probably look a lot nicer in a table.
553 function formatRow( $row ) {
558 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
561 // Create a title for the revision if possible
562 // Rows from the hook may not include title information
563 if ( isset( $row->page_namespace
) && isset( $row->page_title
) ) {
564 $page = Title
::newFromRow( $row );
566 $rev = $this->tryToCreateValidRevision( $row, $page );
568 $attribs['data-mw-revid'] = $rev->getId();
570 $link = $linkRenderer->makeLink(
572 $page->getPrefixedText(),
573 [ 'class' => 'mw-contributions-title' ],
574 $page->isRedirect() ?
[ 'redirect' => 'no' ] : []
576 # Mark current revisions
578 $user = $this->getUser();
580 if ( $row->rev_id
=== $row->page_latest
) {
581 $topmarktext .= '<span class="mw-uctop">' . $this->messages
['uctop'] . '</span>';
582 $classes[] = 'mw-contributions-current';
584 if ( !$row->page_is_new
&& $page->quickUserCan( 'rollback', $user )
585 && $page->quickUserCan( 'edit', $user )
587 $this->preventClickjacking();
588 $topmarktext .= ' ' . Linker
::generateRollback( $rev, $this->getContext() );
591 # Is there a visible previous revision?
592 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) && $rev->getParentId() !== 0 ) {
593 $difftext = $linkRenderer->makeKnownLink(
595 new HtmlArmor( $this->messages
['diff'] ),
596 [ 'class' => 'mw-changeslist-diff' ],
599 'oldid' => $row->rev_id
603 $difftext = $this->messages
['diff'];
605 $histlink = $linkRenderer->makeKnownLink(
607 new HtmlArmor( $this->messages
['hist'] ),
608 [ 'class' => 'mw-changeslist-history' ],
609 [ 'action' => 'history' ]
612 if ( $row->rev_parent_id
=== null ) {
613 // For some reason rev_parent_id isn't populated for this row.
614 // Its rumoured this is true on wikipedia for some revisions (T36922).
615 // Next best thing is to have the total number of bytes.
616 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
617 $chardiff .= Linker
::formatRevisionSize( $row->rev_len
);
618 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
621 if ( isset( $this->mParentLens
[$row->rev_parent_id
] ) ) {
622 $parentLen = $this->mParentLens
[$row->rev_parent_id
];
625 $chardiff = ' <span class="mw-changeslist-separator"></span> ';
626 $chardiff .= ChangesList
::showCharacterDifference(
631 $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
634 $lang = $this->getLanguage();
635 $comment = $lang->getDirMark() . Linker
::revComment( $rev, false, true, false );
636 $date = $lang->userTimeAndDate( $row->rev_timestamp
, $user );
637 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
638 $d = $linkRenderer->makeKnownLink(
641 [ 'class' => 'mw-changeslist-date' ],
642 [ 'oldid' => intval( $row->rev_id
) ]
645 $d = htmlspecialchars( $date );
647 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
648 $d = '<span class="history-deleted">' . $d . '</span>';
651 # Show user names for /newbies as there may be different users.
652 # Note that only unprivileged users have rows with hidden user names excluded.
653 # When querying for an IP range, we want to always show user and user talk links.
655 if ( ( $this->contribs
== 'newbie' && !$rev->isDeleted( Revision
::DELETED_USER
) )
656 ||
$this->isQueryableRange( $this->target
) ) {
657 $userlink = ' <span class="mw-changeslist-separator"></span> '
658 . $lang->getDirMark()
659 . Linker
::userLink( $rev->getUser(), $rev->getUserText() );
660 $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
661 Linker
::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
665 if ( $rev->getParentId() === 0 ) {
666 $flags[] = ChangesList
::flag( 'newpage' );
669 if ( $rev->isMinor() ) {
670 $flags[] = ChangesList
::flag( 'minor' );
673 $del = Linker
::getRevDeleteLink( $user, $rev, $page );
678 // While it might be tempting to use a list here
679 // this would result in clutter and slows down navigating the content
680 // in assistive technology.
681 // See https://phabricator.wikimedia.org/T205581#4734812
682 $diffHistLinks = Html
::rawElement( 'span',
683 [ 'class' => 'mw-changeslist-links' ],
684 // The spans are needed to ensure the dividing '|' elements are not
685 // themselves styled as links.
686 Html
::rawElement( 'span', [], $difftext ) .
687 ' ' . // Space needed for separating two words.
688 Html
::rawElement( 'span', [], $histlink )
692 list( $tagSummary, $newClasses ) = ChangeTags
::formatSummaryRow(
697 $classes = array_merge( $classes, $newClasses );
699 Hooks
::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
704 'diffHistLinks' => $diffHistLinks,
705 'charDifference' => $chardiff,
707 'articleLink' => $link,
708 'userlink' => $userlink,
709 'logText' => $comment,
710 'topmarktext' => $topmarktext,
711 'tagSummary' => $tagSummary,
714 # Denote if username is redacted for this edit
715 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
716 $templateParams['rev-deleted-user-contribs'] =
717 $this->msg( 'rev-deleted-user-contribs' )->escaped();
720 $ret = $this->templateParser
->processTemplate(
721 'SpecialContributionsLine',
726 // Let extensions add data
727 Hooks
::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
728 $attribs = array_filter( $attribs,
729 [ Sanitizer
::class, 'isReservedDataAttribute' ],
733 // TODO: Handle exceptions in the catch block above. Do any extensions rely on
734 // receiving empty rows?
736 if ( $classes === [] && $attribs === [] && $ret === '' ) {
737 wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
738 return "<!-- Could not format Special:Contribution row. -->\n";
740 $attribs['class'] = $classes;
742 // FIXME: The signature of the ContributionsLineEnding hook makes it
743 // very awkward to move this LI wrapper into the template.
744 return Html
::rawElement( 'li', $attribs, $ret ) . "\n";
748 * Overwrite Pager function and return a helpful comment
751 function getSqlComment() {
752 if ( $this->namespace ||
$this->deletedOnly
) {
753 // potentially slow, see CR r58153
754 return 'contributions page filtered for namespace or RevisionDeleted edits';
756 return 'contributions page unfiltered';
760 protected function preventClickjacking() {
761 $this->preventClickjacking
= true;
767 public function getPreventClickjacking() {
768 return $this->preventClickjacking
;
772 * Set up date filter options, given request data.
774 * @param array $opts Options array
775 * @return array Options array with processed start and end date filter options
777 public static function processDateFilter( array $opts ) {
778 $start = $opts['start'] ??
'';
779 $end = $opts['end'] ??
'';
780 $year = $opts['year'] ??
'';
781 $month = $opts['month'] ??
'';
783 if ( $start !== '' && $end !== '' && $start > $end ) {
789 // If year/month legacy filtering options are set, convert them to display the new stamp
790 if ( $year !== '' ||
$month !== '' ) {
791 // Reuse getDateCond logic, but subtract a day because
792 // the endpoints of our date range appear inclusive
793 // but the internal end offsets are always exclusive
794 $legacyTimestamp = ReverseChronologicalPager
::getOffsetDate( $year, $month );
795 $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601
) );
796 $legacyDateTime = $legacyDateTime->modify( '-1 day' );
798 // Clear the new timestamp range options if used and
799 // replace with the converted legacy timestamp
801 $end = $legacyDateTime->format( 'Y-m-d' );
804 $opts['start'] = $start;